import axios from 'axios' // 引入axios
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import { emitter } from '@/utils/bus.js'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 120000
})
let activeAxios = 0
let timer
const showLoading = () => {
  activeAxios++
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    if (activeAxios > 0) {
      emitter.emit('showLoading')
    }
  }, 400)
}

const closeLoading = () => {
  activeAxios--
  if (activeAxios <= 0) {
    clearTimeout(timer)
    emitter.emit('closeLoading')
  }
}
// http request 请求拦截器
service.interceptors.request.use(
  config => {
    if (!config.donNotShowLoading) {
      showLoading()
    }
    const userStore = useUserStore()

    config.headers['Authorization'] = userStore.token

    return config
  },
  error => {
    closeLoading()
    ElMessage({
      message: error,
      type: 'error'
    })
    return error
  }
)

// http response 响应拦截器
service.interceptors.response.use(
  response => {
    const userStore = useUserStore()
    closeLoading()
    // 对统一返回的数据格式进行处理
    const {
      /* 只有请求参数存在这项配置的时候才会生效,其类型定义为 export type DataConversion = boolean | ((res: Result) => any) */
      config: { dataConversion }
    } = response
    let conversion
    if (typeof dataConversion === 'function') {
      /* 函数方式为自定义转换 */
      conversion = dataConversion
    } else if (!!dataConversion) {
      /* true 使用默认方式转换 */
      conversion = res => res['data']
    }
    if (conversion) {
      /* 错误处理 */
      const { succeed, msg = '服务器内部错误' } = response.data
      if (succeed) {
        return conversion(response.data)
      } else {
        ElMessage({
          message: msg,
          type: 'error',
          duration: 10 * 1000
        })
        return response.data
      }
    }

    if (response.status === 200) {
      if (
        response.data.code === 200 ||
        (response.data.status === 200 && response.data.succeed) ||
        response.request.responseType === 'blob'
      ) {
        if (response.config.url === '/auth/login') {
          userStore.setToken(response.data.data.token)
        }
      } else if (
        response.data.status === 1001 ||
        response.data.status === 1002 ||
        response.data.status === 1003 ||
        response.data.status === 1004 ||
        response.data.status === 1005
      ) {
        return response.data
      } else {
        ElMessage({
          message: response.data.msg || '系统异常',
          type: 'error',
          duration: 10 * 1000
        })
      }
      return response.data
    } else {
      ElMessage({
        message: response.data.msg || '系统异常',
        type: 'error',
        duration: 10 * 1000
      })
      return response.data
    }
  },
  error => {
    const userStore = useUserStore()
    closeLoading()
    if (!error.response) {
      ElMessageBox.confirm(
        `
        <p>检测到请求错误</p>
        <p>${error}</p>
        `,
        '请求报错',
        {
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          confirmButtonText: '稍后重试',
          cancelButtonText: '取消'
        }
      )
      return
    }

    switch (error.response.status) {
      // 捕获常见异常
      case 500:
        ElMessage({
          message: error.response.data.msg || '请求异常',
          type: 'error'
        })
        break
      case 404:
        ElMessageBox.confirm(
          `
          <p>检测到接口错误${error}</p>
          <p>错误码<span style='color:red'> 404 </span>：此类错误多为接口未注册（或未重启）或者请求路径（方法）与api路径（方法）不符</p>
          `,
          '接口报错',
          {
            dangerouslyUseHTMLString: true,
            distinguishCancelAndClose: true,
            confirmButtonText: '我知道了',
            cancelButtonText: '取消'
          }
        )
        break
      case 401:
        userStore.LoginOut()
        ElMessage({
          message: error.response.data.msg || '请求异常',
          type: 'error'
        })
        break
      default:
        ElMessage({
          message: error.response.data.msg || '请求异常',
          type: 'error'
        })
    }
    // ElMessage({
    //   message: error.response.data.msg,
    //   type: 'error'
    // })
    return error
  }
)
export default service
